mongodb安装与帮助

使用mongo第一步就是安装,安装之后则是帮助。

官网

当然,最权威的还是官网
官方wiki

安装

  • 官网安装方式
  • 安装之后可以将mongodb的bin目录增加到PATH目录中
  • 例如mac:只需要brew install mongodb,
    然后将/usr/local/Cellar/mongodb/3.4.2/bin加入到path中即可

启动

  • 创建目录
    demo:
/chimps/web_back/mongodb ll
drwxr-xr-x   3 chimp  wheel  102  3 21 14:01 conf
drwxr-xr-x  20 chimp  wheel  680  3 21 14:32 data
drwxr-xr-x   4 chimp  wheel  136  3 21 14:07 log
  • 增加conf文件
    此时没有增加用户认证,生产环境肯定要加的
/chimps/web_back/mongodb cat conf/mongod.conf
port = 12345
dbpath = data
logpath = log/mongod.log
fork = true
  • 运行mongod -f /conf/mongod.conf
    之前将/usr/local/Cellar/mongodb/3.4.2/bin加入到PATH中,mongod可执行文件就在此目录下
  • 日志存放在log/mongod.log
/chimps/web_back/mongodb tail -f log/mongod.log
2017-03-21T14:07:03.850+0800 I -        [initandlisten] Detected data files in /chimps/web_back/mongodb/data created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
... ...

连接

mongo -h

~ mongo -h
MongoDB shell version v3.4.2
usage: mongo [options] [db address] [file names (ending in .js)]    # 格式
db address can be:
  foo                   foo database on local machine
  192.168.0.5/foo       foo database on 192.168.0.5 machine
  192.168.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
Options:
  --shell                             run the shell after executing files
  --nodb                              don't connect to mongod on startup - no
                                      'db address' arg expected
  --norc                              will not run the ".mongorc.js" file on
                                      start up
  --quiet                             be less chatty
  --port arg                          port to connect to
  --host arg                          server to connect to
  --eval arg                          evaluate javascript
  -h [ --help ]                       show this usage information
  --version                           show version information
  --verbose                           increase verbosity
  --ipv6                              enable IPv6 support (disabled by default)
  --disableJavaScriptJIT              disable the Javascript Just In Time
                                      compiler
  --disableJavaScriptProtection       allow automatic JavaScript function
                                      marshalling
  --ssl                               use SSL for all connections
  --sslCAFile arg                     Certificate Authority file for SSL
  --sslPEMKeyFile arg                 PEM certificate/key file for SSL
  --sslPEMKeyPassword arg             password for key in PEM file for SSL
  --sslCRLFile arg                    Certificate Revocation List file for SSL
  --sslAllowInvalidHostnames          allow connections to servers with
                                      non-matching hostnames
  --sslAllowInvalidCertificates       allow connections to servers with invalid
                                      certificates
  --sslFIPSMode                       activate FIPS 140-2 mode at startup
  --networkMessageCompressors arg     Comma-separated list of compressors to
                                      use for network messages
  --jsHeapLimitMB arg                 set the js scope's heap size limit

Authentication Options:
  -u [ --username ] arg               username for authentication
  -p [ --password ] arg               password for authentication
  --authenticationDatabase arg        user source (defaults to dbname)
  --authenticationMechanism arg       authentication mechanism
  --gssapiServiceName arg (=mongodb)  Service name to use when authenticating
                                      using GSSAPI/Kerberos
  --gssapiHostName arg                Remote host name to use for purpose of
                                      GSSAPI/Kerberos authentication

file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
  • 只需要:mongo localhost:12345

数据库操作

  • db.help()
> db.help()
DB methods:
    db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
    db.auth(username, password)
    db.cloneDatabase(fromhost)
    db.commandHelp(name) returns the help for the command
    db.copyDatabase(fromdb, todb, fromhost)
    db.createCollection(name, { size : ..., capped : ..., max : ... } )
    db.createView(name, viewOn, [ { $operator: {...}}, ... ], { viewOptions } )
    db.createUser(userDocument)
    db.currentOp() displays currently executing operations in the db
    db.dropDatabase()
    db.eval() - deprecated
    db.fsyncLock() flush data to disk and lock server for backups
    db.fsyncUnlock() unlocks server following a db.fsyncLock()
    db.getCollection(cname) same as db['cname'] or db.cname
    db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
    db.getCollectionNames()
    db.getLastError() - just returns the err msg string
    db.getLastErrorObj() - return full status object
    db.getLogComponents()
    db.getMongo() get the server connection object
    db.getMongo().setSlaveOk() allow queries on a replication slave server
    db.getName()
    db.getPrevError()
    db.getProfilingLevel() - deprecated
    db.getProfilingStatus() - returns if profiling is on and slow threshold
    db.getReplicationInfo()
    db.getSiblingDB(name) get the db at the same server as this one
    db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
    db.hostInfo() get details about the server's host
    db.isMaster() check replica primary status
    db.killOp(opid) kills the current operation in the db
    db.listCommands() lists all the db commands
    db.loadServerScripts() loads all the scripts in db.system.js
    db.logout()
    db.printCollectionStats()
    db.printReplicationInfo()
    db.printShardingStatus()
    db.printSlaveReplicationInfo()
    db.dropUser(username)
    db.repairDatabase()
    db.resetError()
    db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
    db.serverStatus()
    db.setLogLevel(level,<component>)
    db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
    db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
    db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db
    db.setVerboseShell(flag) display extra information in shell output
    db.shutdownServer()
    db.stats()
    db.version() current version of the server
  • collection 相关操作
    假设我有个user 字段
> db.user.help()
DBCollection help
    db.user.find().help() - show DBCursor help
    db.user.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
    db.user.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    db.user.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
    db.user.convertToCapped(maxBytes) - calls {convertToCapped:'user', size:maxBytes}} command
    db.user.createIndex(keypattern[,options])
    db.user.createIndexes([keypatterns], <options>)
    db.user.dataSize()
    db.user.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
    db.user.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
    db.user.distinct( key, query, <optional params> ) - e.g. db.user.distinct( 'x' ), optional parameters are: maxTimeMS
    db.user.drop() drop the collection
    db.user.dropIndex(index) - e.g. db.user.dropIndex( "indexName" ) or db.user.dropIndex( { "indexKey" : 1 } )
    db.user.dropIndexes()
    db.user.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
    db.user.explain().help() - show explain help
    db.user.reIndex()
    db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
    db.user.find(...).count()
    db.user.find(...).limit(n)
    db.user.find(...).skip(n)
    db.user.find(...).sort(...)
    db.user.findOne([query], [fields], [options], [readConcern])
    db.user.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
    db.user.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.user.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.user.getDB() get DB object associated with collection
    db.user.getPlanCache() get query plan cache associated with collection
    db.user.getIndexes()
    db.user.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
    db.user.insert(obj)
    db.user.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
    db.user.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
    db.user.mapReduce( mapFunction , reduceFunction , <optional params> )
    db.user.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
    db.user.remove(query)
    db.user.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.user.renameCollection( newName , <dropTarget> ) renames the collection.
    db.user.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
    db.user.save(obj)
    db.user.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
    db.user.storageSize() - includes free space allocated to this collection
    db.user.totalIndexSize() - size in bytes of all the indexes
    db.user.totalSize() - storage allocated for all data and indexes
    db.user.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi
    db.user.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.user.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
    db.user.validate( <full> ) - SLOW
    db.user.getShardVersion() - only for use with sharding
    db.user.getShardDistribution() - prints statistics about data distribution in the cluster
    db.user.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
    db.user.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
    db.user.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
    db.user.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
    db.user.latencyStats() - display operation latency histograms for this collection

个人博客:http://notes.xbug.site

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容

  • How have you been ?now i have returned home . I am writin...
    复_383b阅读 312评论 0 0
  • 今天我想和你们谈谈我认识的一个女生,三个月前认识了一个同校学姐,根据这段时间我对她的了解。 她有点虚荣有点好胜有点...
    294cfe96d700阅读 309评论 0 2
  • 【01/25/2017 周三 第147天】 ✔静√智√勇√仁√强√礼 小结。 √早上和狗狗欢欢玩,然后到爸爸朋友郭...
    妈妈熊阅读 184评论 0 0
  • “秋子姐姐,快点来啊,我们都在大巷子里等你~”远处巷子外的小孩子们伸手做喇叭状在不停呼唤着。 秋子...
    南方没有雪梨花阅读 625评论 0 0